package com.example.kotlin.download

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Binder
import android.os.Build
import android.os.Environment
import androidx.core.app.NotificationCompat
import com.example.kotlin.R
import com.example.kotlin.showToast
import com.example.kotlin.ui.HomeActivity
import java.io.File

/**
 * @ClassName: DownloadBinder
 * @Description: java类作用描述
 * @Author: chenmengjia
 * @Date: 2022/2/23 14:43
 */
class DownloadBinder(
    var downloadTask: DownloadTask?,
    var downloadUrl: String?,
    var listener: DownloadListener?, private val context: Service
) : Binder() {

    fun startDownload(url: String) {
        if (downloadTask == null) {
            downloadUrl = url

            downloadTask = DownloadTask(listener)
            downloadTask?.execute(url)
            context.startForeground(1, getNotification("正在下载", 0))
            context.showToast("正在下载中")
        }
    }

    fun pauseDownLoad() {

        downloadTask?.pauseDownload()


    }

    fun cancelDownLoad() {

        if (downloadTask != null) {
            downloadTask?.cancelDownload()

        } else {


            //取消下载时将文件删除

            downloadUrl?.run {
                val fileName = substring(lastIndexOf("/"))
                val directory =
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).path
                val file = File(directory + fileName)
                if (file.exists()) {
                    file.delete()
                }
                getNotificationManager().cancel(1)
                context.stopForeground(true)
                context.showToast("取消下载")
            }


        }

    }

    private fun getNotificationManager() =
        context.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager

    private fun getNotification(title: String, progress: Int): Notification {
        val channelId = "default"
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val channel =
                NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_DEFAULT)
            val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            nm?.let {
                if (it.getNotificationChannel(channelId) == null) {//没有创建
                    it.createNotificationChannel(channel)//则先创建
                }
            }
        }
        val intent = Intent(context, HomeActivity::class.java)
        val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
        val builder: NotificationCompat.Builder = NotificationCompat.Builder(context,channelId)
        builder.setSmallIcon(R.mipmap.ic_launcher)
        builder.setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
        builder.setContentIntent(pendingIntent)
        builder.setContentTitle(title)
       // builder.setChannelId(channelId)
        if (progress > 0) {
            builder.setContentText("$progress%")
            builder.setProgress(100, progress, false)
        }
        return builder.build()

    }
}